var express = require("express")
var router = express.Router()
var Category = require("../models/category")
var Content = require("../models/content")

//首页
router.get('/', function (req, res, next) {

    var data = {
        page: Number(req.query.page || 1),
        limit: 10,
        pages: 0,
        count: 0,
        category: req.query.type || "",
        userInfo: req.userInfo,
        categorys: [],
        contents: []
    }
    // console.log(data.category)
    //读取所有的分类信息
    Category.find().sort({ _id: -1 }).then(function (categorys) {
        // console
        data.categorys = categorys
        return Content.count()
    }).then(function (count) {
        data.count = count
        data.pages = Math.ceil(data.count / data.limit)
        data.page = Math.min(data.page, data.pages)
        data.page = Math.max(data.page, 1)
        var skip = (data.page - 1) * data.limit
        //根据where来显示分类信息
        var where = {}
        if (data.category) {
            where.category = data.category
        }
        return Content.where(where).find().limit(data.limit).skip(skip).populate(["category", "user"])
    }).then(function (contents) {
        data.contents = contents
        res.render('main/index.html', data)
    })
})

// /views?page={{content.id}}显示详细信息
router.get("/views",function(req,res){
    var id = req.query.page
    Content.findOne({
        _id:id
    }).then(function(content){
        //增加点击量
        content.view++;
        content.save()
        res.render("main/detail",{
            content:content,
            userInfo:req.userInfo
        })
    })
})

module.exports = router